import * as API from "@/api";
import {
  getSessionObjStore,
  setSessionObjStore,
  setSessionStore,
  getSessionStore,
  setCookie,
  getCookie,
  setCookieObj,
  getCookieObj
} from "@/libs/util";

export default {
  state: {
    userInfo: getCookieObj("userInfo") ? getCookieObj("userInfo") : "",
    token: getCookie("token"),
    role: getCookieObj("role"), //角色是数组，可以多重角色，一个账号
    messageCount: 0
  },
  mutations: {
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo;
      setCookieObj("userInfo", userInfo);
    },
    setToken(state, token) {
      state.token = token;
      setCookie("token", token);
    },
    setRole(state, role) {
      state.role = role;
      setCookieObj("role", role);
    }
  },
  actions: {
    //退出登录
    handleLogOut({ state, commit }) {
      return new Promise((resolve, reject) => {
        API.logout(state.token)
          .then(() => {
            commit("setUserInfo", "");
            commit("setToken", "");
            commit("setRole", "");
            //------------------------------
            //commit("setRouter", []);
            commit("setTagNavList", []);
            commit("breadCrumbList", []);
            resolve();
          })
          .catch(err => {
            reject(err);
          });
      });
    },

    //客户端单方面退出.如需后台退出，请调用退出API后在调用该action
    handleClientLogOut({ state, commit }) {
      commit("setUserInfo", "");
      commit("setToken", "");
      commit("setRole", "");
      //commit("setRouter", []); 退出后，马上在登录存在，router已经不在，路由异常
      commit("setTagNavList", []);
      commit("breadCrumbList", []);
      //-----------------------
      //sessionStorage.clear();
      //localStorage.clear();
    },

    // 修改密码
    editUserPw({ state, commit }, obj) {
      return new Promise((resolve, reject) => {
        API.editPW(obj)
          .then(res => {
            resolve(res);
          })
          .catch(err => {
            reject(err);
          });
      });
    }
  }
};
